<template>
  <transition appear enter-active-class="animated fadeIn">
    <div class="scroll-wrap" ref="scrollWrap">
      <scroll
        class="usercenter"
        ref="scrollContent"
        :listen-scroll="listenScroll"
        @scroll="scroll"
        :probeType="probeType"
      >
        <div class="usercenter-in">
          <!-- 登录后用户个人中心 -->
          <!-- 背景： -->
          <div class="user-centerbg">
            <div class="user-info-row">
              <div class="user-info">
                <div class="user-avatar">
                  <img :src="userInfo.avatarUrl" alt />
                </div>
                <div class="user-name">
                  <h6>{{userInfo.nickname}}</h6>
                  <div class="vip-info">
                    <i class="iconfont iconVIP1" :class="vipType"></i>
                    <span>Lv.{{this.level}}</span>
                  </div>
                </div>
              </div>
              <div class="sign-in" @click="handleClickSign" :class="isSignCls">
                <i class="iconfont iconqiandao" v-if="mobileSign"></i>
                <span v-if="!mobileSign">签到</span>
                <span v-if="mobileSign">已签到</span>
              </div>
            </div>
            <!-- 用户工具 -->
            <div class="user-tool">
              <div class="tool-item" @click="handleSync">
                <i class="iconfont iconiconfontzhizuobiaozhunbduan23"></i>
                <p>同步离线</p>
              </div>
              <div class="tool-item">
                <i class="iconfont iconzhanghaodenglu" @click="touserInfo"></i>
                <p>账号信息</p>
              </div>
              <div class="tool-item">
                <i class="iconfont iconxiaoxi"></i>
                <p>我的消息</p>
              </div>
              <div class="tool-item" @click="handleSwitch">
                <i class="iconfont iconqiehuan"></i>
                <p>切换账号</p>
              </div>
            </div>
            <div
              class="user-centerbg-image"
              :style="{backgroundImage:'url('+userInfo.backgroundUrl+')'}"
            >
              <div class="filter"></div>
            </div>
          </div>
          <div class="user-songsheet">
            <!-- 用户歌单： -->
            <div class="my-music w700">
              <h4>我的音乐</h4>
              <div class="my-music-list">
                <div
                  class="favorite-music item"
                  @click="selectItemlikesong"
                  :style="{backgroundImage:'url('+userInfo.backgroundUrl+')'}"
                >
                  <div class="bg-mask"></div>
                  <i class="iconfont iconlike"></i>
                  <p>我喜欢的音乐</p>
                  <div class="support-tit circle">心动模式</div>
                </div>
                <div class="music-fm item" @click="selectItemFM">
                  <div class="bg-mask" style="background-color:#e9e8e9"></div>
                  <i class="iconfont iconFM"></i>
                  <p>私人FM</p>
                  <div class="support-tit">超三亿人听</div>
                </div>
                <div class="music-hot item" @click="selectRecommend">
                  <div class="bg-mask" style="background-color:#d2cfd2"></div>
                  <i class="iconfont iconhuo"></i>
                  <p>每日推荐</p>
                  <div class="support-tit">寻找音乐伯乐</div>
                </div>
              </div>
            </div>
            <van-loading
              v-show="!allsongsheet.length"
              type="circular"
              color="#fff"
              vertical
            >正在加载用户歌单...</van-loading>
            <User-songsheet :sheets="allsongsheet" @updateSheet="handleUpdateSheet"></User-songsheet>
          </div>
        </div>
      </scroll>
    </div>
  </transition>
</template>

<script>
import Scroll from "@/base/scroll/scroll";
import { mapGetters, mapActions, mapMutations } from "vuex";
import {
  getUserDetail,
  getUserSubcount,
  getUserSongSheet,
  signIn,
  getPersonFM,
  getPersonRecommend,
  likeMusic,
  getSongSheet
} from "@/request/api";
import { createSearchSongs } from "@/common/song.js";
import UserSongsheet from "./userSongsheet";
import { playListMixin } from "@/common/mixin.js";
import PubSub from "pubsub-js";
import { delCookie } from "@/utils/cookie";
import { Dialog } from "vant";
export default {
  mixins: [playListMixin],
  data() {
    return {
      level: 0,
      createTime: 0,
      createDays: 0,
      // 全部歌单：
      allsongsheet: [],
      // 喜欢的音乐：
      likesong: {},
      FMsong: {},
      recommendsong: [],
      // 是否签到：
      mobileSign: false,
      // bs滚动的距离
      scrollY: -1
    };
  },
  computed: {
    ...mapGetters([
      "favoriteList",
      "playHistory",
      "userInfo",
      "favoriteListId"
    ]),
    vipType() {
      if (this.userInfo.vipType === 0) {
        return "notVip";
      } else {
        return "isvip";
      }
    },
    isSignCls() {
      return this.mobileSign ? "hasSign" : "";
    }
  },
  created() {
    this.listenScroll = true;
    this.probeType = 3;
    getUserDetail(this.userInfo.userId).then(res => {
      this.level = res.level;
      this.mobileSign = res.mobileSign;
      console.log(res);
    });
    getUserSongSheet(this.userInfo.userId).then(res => {
      this.allsongsheet = res.playlist;
      // 保存喜欢的歌曲：
      this.likesong = res.playlist[0];
    });
  },
  methods: {
    // bs:
    handlePlayList(playlist) {
      const bottom = playlist.length > 0 ? "60px" : "";
      this.$refs.scrollWrap.style.paddingBottom = bottom;
      this.$refs.scrollContent.refresh();
    },
    scroll(pos) {
      // 获取betterscroll滚动的y轴距离
      this.scrollY = pos.y;
    },
    // 点击签到;
    handleClickSign() {
      if (!this.mobileSign) {
        signIn().then(res => {
          if (res.code === 200) {
            this.$toast("签到成功");
            this.mobileSign = true;
          }
        });
      } else {
        this.$toast("请勿重复签到");
      }
    },
    // 点击已喜欢的歌曲
    selectItemlikesong() {
      let item = this.likesong;
      this.$router.push({
        name: "songsheet",
        query: { id: item.id }
      });

      this.setSonngSheet(item);
      this.setSongSheetType("私人歌单");
    },
    // 点击每日推荐：
    selectRecommend() {
      getPersonRecommend().then(res => {
        if (res.code === 200) {
          this.recommendsong = this._normalizeSongs(res.recommend);
          this.selectPlay({
            list: this.recommendsong,
            index: 0
          });
        }
      });
    },
    // 点击FM
    selectItemFM() {
      getPersonFM().then(res => {
        if (res.code === 200) {
          this.FMsong = this._normalizeSongs(res.data);
          this.selectPlay({
            list: this.FMsong,
            index: 0
          });
        }
      });
    },
    // 格式化歌曲：
    _normalizeSongs(list) {
      let ret = [];
      list.forEach(item => {
        if (item.id && item.album.id) {
          ret.push(createSearchSongs(item));
        }
      });
      return ret;
    },
    ...mapActions(["selectPlay", "clearUserDate", "deleteFavoriteAll"]),
    ...mapMutations({
      setSonngSheet: "SET_SONGSHEET",
      setSongSheetType: "SET_SONGSHEET_TYPE",
      setUserLikeList: "SET_USER_LIKELIST"
    }),
    // 点击同步：
    handleSync() {
      if (this.favoriteList.length === 0) {
        this.$toast("离线列表内无喜欢的歌曲，无需同步");
        return;
      }
      Dialog.confirm({
        message: `找到${this.favoriteList.length}首喜欢的离线歌曲，是否同步`,
        className: "dialog_themedark",
        confirmButtonText: "同步",
        width: "250px"
      })
        .then(() => {
          this.syncMusic();
        })
        .catch(() => {});
    },
    // 同步歌曲请求：
    syncMusic() {
      let idlist = this.favoriteListId;
      let flag = 0;
      for (let i = 0; i < idlist.length; i++) {
        likeMusic(idlist[i], {
          like: true
        }).then(res => {
          if (res.code === 200) {
            flag++;
            if (flag === idlist.length - 1) {
              Dialog.confirm({
                message: `同步成功，是否删除离线歌曲`,
                className: "dialog_themedark",
                confirmButtonText: "删除",
                width: "250px"
              })
                .then(() => {
                  this.deleteFavoriteAll();
                })
                .catch(() => {});
            }
          }
        });
      }
    },
    // 切换账号
    handleSwitch() {
      Dialog.confirm({
        message: "是否切换账号",
        className: "dialog_themedark",
        confirmButtonText: "切换",
        width: "250px"
      })
        .then(() => {
          this.$router.push({
            path: "/user/login"
          });
          this.$cookieStore.clearAllCookie();
          this.clearUserDate();
        })
        .catch(() => {
          // this.garbageOpen = false;
        });
    },
    touserInfo() {
      this.$router.push({
        path: "/user/userCenter"
      });
    },
    // 子组件创建新歌单:
    handleUpdateSheet() {
      console.log("更新表单");

      getUserSongSheet(this.userInfo.userId).then(res => {
        this.allsongsheet = res.playlist;
      });
    }
  },
  watch: {
    scrollY(newY) {
      if (newY > 0) {
        // 大于零说明是向上滑动
        PubSub.publish("fixtitle", false);
        return;
      }
      // 小于零说明是向下滑动(当在title区间滚动时候)：
      if (newY < 0 && newY > -45) {
        let distance = parseInt((Math.abs(newY) / 45) * 100) / 100;
        PubSub.publish("titleDistance", distance);
        PubSub.publish("fixtitle", true);
        return false;
      }
      if (newY <= -45) {
        PubSub.publish("fixtitle", true);
        PubSub.publish("titleDistance", 1);
      }
    }
  },
  components: {
    Scroll,
    UserSongsheet,
    [Dialog.Component.name]: Dialog.Component
  }
};
</script>

<style lang="less" scoped>
.scroll-wrap {
  position: absolute;
  height: 100%;
  bottom: 0;
  left: 0;
  // padding-bottom: 60px;
  width: 100%;
}
.usercenter {
  height: 100%;
  overflow: hidden;
  // background-color: #fefefe;
}
.user-centerbg {
  height: 40vh;
  .bz(cover);
  position: relative;
  padding: 0 18px;
  padding-top: 10vh;
  .user-centerbg-image {
    .posfull;
    .bz(cover);
    z-index: -1;
    .filter {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background: rgba(7, 17, 27, 0.4);
    }
  }
}
.user-info-row {
  .flex-nowrap-sb(center);
}
.user-info {
  .flex-row-nowrap(center);
  .user-avatar {
    img {
      width: 60px;
      height: 60px;
      border-radius: 50%;
    }
  }
  .user-name {
    margin-left: 6px;
    h6 {
      font-size: 18px;
    }
    .vip-info {
      margin-top: 8px;
      .flex-row-nowrap(center);
      i {
        font-size: 24px;
        &.notVip {
          opacity: 0.4;
        }
      }
      span {
        font-size: 14px;
        margin-left: 4px;
      }
    }
  }
}
.sign-in {
  font-size: 14px;
  width: 75px;
  text-align: center;
  height: 26px;
  .cf;
  background-color: @color-sub-theme;
  line-height: 24px;
  border-radius: 30px;
  &.hasSign {
    background-color: #333;
  }
  span {
    margin-left: 2px;
    font-size: 12px;
  }
}
.user-songsheet {
  border-top-left-radius: 20px;
  border-top-right-radius: 20px;
}
.my-music {
  h4 {
    font-size: 16px;
    font-weight: bold;
    padding-top: 20px;
    margin-bottom: 15px;
    // color: #333;
  }
}
.my-music-list {
  .flex-nowrap-sb;
  width: 100%;
  .item {
    width: 31%;
    height: 3.8667rem;
    background: #e9e8e9;
    border-radius: 8px;
    text-align: center;
    position: relative;
    overflow: hidden;
    padding-top: 0.65rem;
    .bz(cover);
    .bg-mask {
      .posfull;
      background: rgba(7, 17, 27, 0.2);
    }
    i {
      position: relative;
      color: @color-sub-theme;
      font-size: 0.64rem;
    }
    p {
      position: relative;
      font-size: 14px;
      margin-top: 10px;
    }
    .support-tit {
      font-size: 12px;
      text-align: left;
      position: relative;
      width: 2.08rem;
      height: 0.64rem;
      margin: 0 auto;

      .cf;
      text-align: center;
      line-height: 0.64rem;
      position: absolute;
      left: 0;
      bottom: 12px;
      right: 0;
      &.circle {
        border-radius: 0.3333rem;
        background-color: rgba(0, 0, 0, 0.4);
      }
    }
    &.music-fm {
      i {
        &.iconFM {
          color: #251e27;
        }
      }
      p {
        color: #251e27;
      }
      .support-tit {
        color: #333;
      }
    }
    &.music-hot {
      p {
        color: #333;
      }
      .support-tit {
        color: #333;
      }
    }
  }
}

.user-tool {
  font-size: 16px;
  .flex-nowrap-sb(center);
  position: absolute;
  left: 0;
  right: 0;
  width: 100%;
  bottom: 10%;
  .tool-item {
    flex: 1;
    text-align: center;
    i {
      font-size: 22px;
    }
    p {
      margin-top: 12px;
      font-size: 14px;
      opacity: 0.9;
    }
  }
}
</style>